﻿using TouchSocket.Core;
using TouchSocket.Sockets;

namespace SL651Center2.x
{
    public class TcpServer
    {
        private TcpService _tcpService;

        List<TelemetryInfo> _telemetryInfo;

        public TcpServer()
        {
            _tcpService = new TcpService();
            _telemetryInfo = new List<TelemetryInfo>();
        }

        /// <summary>
        /// 启动TCP服务器
        /// </summary>
        public void Start()
        {
            //_tcpService = new TcpService();
            //有客户端正在连接
            _tcpService.Connecting += (client, e) =>
            {
                Console.WriteLine("客户端正在连接");
                return EasyTask.CompletedTask;
            };
            //客户端连接成功
            _tcpService.Connected += (client, e) =>
            {
                Console.WriteLine($"客户端{client.Id},{client.IP}:{client.Port}连接");
                return EasyTask.CompletedTask;
            };
            _tcpService.Closed += (client, e) =>
            {
                Console.WriteLine($"客户端{client.Id},{client.IP}:{client.Port}断开连接");
                return EasyTask.CompletedTask;
            };

            _tcpService.Setup(new TouchSocketConfig()//载入配置
                .SetListenIPHosts(55000)//监听地址
                .ConfigureContainer(a =>//容器的配置顺序应该在最前面
                {
                    a.AddConsoleLogger();//添加一个控制台日志注入（注意：在maui中控制台日志不可用）
                })
                .ConfigurePlugins(a =>
                {
                    //客户端在线检查
                    /*a.UseCheckClear()
                   .SetCheckClearType(CheckClearType.All)
                   .SetTick(TimeSpan.FromSeconds(60))
                   .SetOnClose((c, t) =>
                   {
                       c.TryShutdown();
                       c.SafeClose("超时无数据");
                   });*/
                    //消息接受插件
                    a.Add<ReceivedMessagePlugin>();

                    //a.Add();//此处可以添加插件
                })
            );

            _tcpService.StartAsync();//启动
            Console.WriteLine("服务器启动!");

        }

        /// <summary>
        /// 停止TCP服务器
        /// </summary>
        public void Stop()
        {
            _tcpService?.StopAsync();
        }

        public string[] GetClientIds()
        {
            var ids = _tcpService.GetIds();
            return ids.ToArray();
        }

        public TcpSessionClient GetClient()
        {
            var ids = _tcpService.GetIds();
            if (_tcpService.TryGetClient(ids.First(s => s == "1111111111"), out TcpSessionClient socketClient))
            {
                return socketClient;
            }
            return null;
        }

        public TcpSessionClient GetClient(string id)
        {
            if (_tcpService.TryGetClient(id, out TcpSessionClient socketClient))
            {
                return socketClient;
            }
            return null;
        }

    }
}
